package com.eversec.util.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * @author lilizhao
 *
 */
public class FtpXmlUtil {
	public static String formatXML(String inputXML) {
		SAXReader reader = new SAXReader();
		String requestXML = null;
		try {
			Document document = reader.read(new StringReader(inputXML));
			requestXML = null;
			XMLWriter writer = null;
			if (document != null) {
				try {
					StringWriter stringWriter = new StringWriter();
					OutputFormat format = new OutputFormat(" ", true);
					writer = new XMLWriter(stringWriter, format);
					writer.write(document);
					writer.flush();
					requestXML = stringWriter.getBuffer().toString();
				} finally {
					if (writer != null) {
						try {
							writer.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return requestXML;
	}
	
	/**
	 * 读取 xml 文件内容
	 * 
	 * @param file
	 *            文件名
	 * @return 文件内容
	 */
	public static String readFile(File file) {
		StringBuilder sb = new StringBuilder();
		FileInputStream fis = null;
		
		try {
			fis = new FileInputStream(file);
			byte[] buf = new byte[1024];
			while ((fis.read(buf)) != -1) {
				sb.append(new String(buf));
				buf = new byte[1024];// 重新生成，避免和上次读取的数据重复
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * 可考虑的方案，待验证
	 * @param file 目标文件
	 * @param content 文件内容
	 */
	public static void writeFileForUTF(File file, String content) {
		XMLWriter output = null;
		try {
			OutputFormat outFmt = new OutputFormat("\t", true);
			outFmt.setEncoding("UTF-8");
			output = new XMLWriter(new FileOutputStream(file), outFmt);
			output.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 写文件的方法
	 * @param file 目标文件
	 * @param content 文件内容
	 * @return 是否正常写文件
	 */
	public static void writeFile(File file, String content) {
		OutputStreamWriter osw = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			osw = new OutputStreamWriter(new FileOutputStream(file, false),"UTF-8");
			osw.write(content);
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}